package com.sdk.springbootjwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import lombok.Data;

import java.util.Date;

@Data
public class JwtUtil {
    private static final String SECRET = "your-256-bit-secret";
    public static final long ACCESS_EXPIRE = 30 * 60 * 1000; // 30分钟
    public static final long REFRESH_EXPIRE = 7 * 24 * 60 * 60 * 1000; // 7天

    // 生成AccessToken
    public static String generateAccessToken(String username) {
        return JWT.create()
                .withSubject(username)
                .withExpiresAt(new Date(System.currentTimeMillis() + ACCESS_EXPIRE))
                .sign(Algorithm.HMAC256(SECRET));
    }

    // 生成RefreshToken
    public static String generateRefreshToken(String username) {
        return JWT.create()
                .withSubject(username)
                .withExpiresAt(new Date(System.currentTimeMillis() + REFRESH_EXPIRE))
                .sign(Algorithm.HMAC256(SECRET));
    }

    // 验证Token
    public static String validateToken(String token) throws JWTVerificationException {
        return JWT.require(Algorithm.HMAC256(SECRET))
                .build()
                .verify(token)
                .getSubject();
    }

    public static long getRemainingTime(String oldAccessToken) {
        return JWT.require(Algorithm.HMAC256(SECRET))
                .build()
                .verify(oldAccessToken)
                .getExpiresAt().getTime() - System.currentTimeMillis();
    }
}

